package com.wwwarehouse.usercenter.fragment.register;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.Spannable;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.CharacterByteUtils;
import com.wwwarehouse.common.tools.CheckUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tools.rsa.Base64Utils;
import com.wwwarehouse.common.tools.rsa.RSAUtil;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.common.UserCenterCommon;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import de.greenrobot.event.EventBus;

/**
 * 用户名和密码
 * Created by xiaoke.ni on 2017/8/11.
 */
public class RCUserNamePasswordFragment extends RegisterCardBaseFragment implements View.OnClickListener, TextWatcher, ClearEditText.onMyFocusChangeListener {
    private View          mRootView;
    private ClearEditText mUsernameEdt;
    private ClearEditText mPasswordEdt;
    private ImageView     mEyeImg;

    private boolean mIsEyeOpened = false;

    private Button mSubmitBtn;

    private static final int REQUEST_CHECK_USER_ACCOUNT = 0;
    private TextInputLayout mTilUseName;
    private TextInputLayout mTilPassword;
    private View            mViewPassword;
    private boolean mIsLetterDigit = true;
    private ClearEditText   mPasswordAgainEdt;
    private View            mViewPasswordAgain;
    private RelativeLayout  mRlEye;
    private RelativeLayout  mRlElse;
    private TextInputLayout mTilPasswordAgain;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_rc_user_name_password, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initEvent();
    }

    private void initView() {
        mUsernameEdt = findView(mRootView, R.id.et_username);
        setEditTextInhibitInputSpace(mUsernameEdt, 30);
        //        CharacterByteUtils.limitLength(mUsernameEdt, 30);
        //        mUsernameEdt.setFilters(new InputFilter[]{UserCenterCheckUtils.limitLength(30)});
        mPasswordEdt = findView(mRootView, R.id.et_password);
        mPasswordEdt.setLongClickable(false);
        mPasswordEdt.setTextIsSelectable(false);
        mPasswordEdt.setOnMyFocusChangeListener(this);
        mEyeImg = findView(mRootView, R.id.iv_eye);
        mRlEye = findView(mRootView, R.id.rl_eye);
        mRlEye.setOnClickListener(this);
        mTilUseName = findView(mRootView, R.id.til_username);
        mTilPassword = findView(mRootView, R.id.til_password);
        mViewPassword = findView(mRootView, R.id.view_password);
        mSubmitBtn = findView(mRootView, R.id.btn_submit);
        mPasswordAgainEdt = findView(mRootView, R.id.et_password_again);
        mPasswordAgainEdt.setOnMyFocusChangeListener(this);
        mPasswordAgainEdt.setLongClickable(false);
        mPasswordAgainEdt.setTextIsSelectable(false);
        mTilPasswordAgain = findView(mRootView, R.id.til_password_again);
        mRlElse = findView(mRootView, R.id.rl_else);
        if (UserCenterCommon.getInstance().getUserAccount() != null) {
            mUsernameEdt.setText(UserCenterCommon.getInstance().getUserAccount().toString().trim());
            mTilUseName.updateLabelState();
        }
        if (UserCenterCommon.getInstance().getPasswordCanSee() != null) {
            mPasswordEdt.setText(UserCenterCommon.getInstance().getPasswordCanSee().toString().trim());
            mPasswordAgainEdt.setText(UserCenterCommon.getInstance().getPasswordCanSee().toString().trim());
            mTilPassword.updateLabelState();
            mTilPasswordAgain.updateLabelState();
        }
        if (UserCenterCommon.getInstance().getUserAccount() != null && UserCenterCommon.getInstance().getPasswordCanSee() != null) {
            mSubmitBtn.setEnabled(true);
            mSubmitBtn.setBackgroundResource(R.drawable.common_btn2_solid_selector);
        }
    }

    private void initEvent() {
        mUsernameEdt.addTextChangedListener(this);
        mPasswordEdt.addTextChangedListener(this);
        mPasswordAgainEdt.addTextChangedListener(this);
        //        mEyeImg.setOnClickListener(this);

        mSubmitBtn.setOnClickListener(this);
        mRlElse.setOnClickListener(this);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof RCUserNamePasswordFragment) {
            mActivity.setTitle(R.string.user_name_password);
        }
    }

    @Override
    public void requestDatas() {

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.rl_eye) {
            if (!mIsEyeOpened) {
                mEyeImg.setImageResource(R.drawable.register_open_eyes);
                mPasswordEdt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                mPasswordAgainEdt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                mEyeImg.setImageResource(R.drawable.register_close_eye);
                mPasswordEdt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                mPasswordAgainEdt.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }

            mPasswordEdt.postInvalidate();
            mPasswordAgainEdt.postInvalidate();
            mIsEyeOpened = !mIsEyeOpened;

            CharSequence charSequence = mPasswordEdt.getText();
            if (charSequence instanceof Spannable) {
                Spannable spannable = (Spannable) charSequence;
                Selection.setSelection(spannable, charSequence.length());
            }
            CharSequence charSequence1 = mPasswordAgainEdt.getText();
            if (charSequence1 instanceof Spannable) {
                Spannable spannable1 = (Spannable) charSequence1;
                Selection.setSelection(spannable1, charSequence1.length());
            }

        } else if (i == R.id.btn_submit) {//清除一下焦点 使之能走onTextChanged方法
            if (!TextUtils.equals(mPasswordEdt.getText().toString().trim(), mPasswordAgainEdt.getText().toString().trim())) {
                ToastUtils.showToast("两次密码输入不一致, 请重新输入");
                return;
            }
            mPasswordEdt.clearFocus();
            mUsernameEdt.clearFocus();
            mPasswordAgainEdt.clearFocus();
            checkUerAccount();
            //            mIsLetterDigit = CheckUtils.isLetterDigit(mPasswordEdt.getText().toString().trim());
            //            if (mPasswordEdt.getText().toString().trim().equals(mPasswordAgainEdt.getText().toString().trim())) {
            //                if (mIsLetterDigit && mPasswordEdt.getText().toString().trim().length() >= 6 && mPasswordEdt.getText().toString().trim().length() <= 16) {
            //                    //请求接口
            //
            //                } else {
            //                    mTilPassword.setStateWrong(getResources().getString(R.string.wrong_password));
            //                    mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
            //                }
            //            } else {
            //                mTilPassword.setStateWrong(getResources().getString(R.string.password_not_same));
            //                mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
            //            }
        } else if (i == R.id.rl_else) {
            if (mPasswordEdt.isFocusable()) {
                mPasswordEdt.clearFocus();
            }
            if (mPasswordAgainEdt.isFocusable()) {
                mPasswordAgainEdt.clearFocus();
            }
            hideSoftKeyBoard(v);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(mUsernameEdt.getText().toString().trim()) &&
                !TextUtils.isEmpty(mPasswordEdt.getText().toString().trim()) && !TextUtils.isEmpty(mPasswordAgainEdt.getText().toString().trim())) {
            mSubmitBtn.setEnabled(true);
            mSubmitBtn.setBackgroundResource(R.drawable.common_btn2_solid_selector);

        } else {
            mSubmitBtn.setEnabled(false);
            mSubmitBtn.setBackgroundResource(R.drawable.common_btn1_noclick_shape);
        }
        if (!TextUtils.isEmpty(mUsernameEdt.getText().toString())) {
            String str = stringFilter(mUsernameEdt.getText().toString());
            if(!mUsernameEdt.getText().toString().equals(str)){
                mUsernameEdt.setText(str);
                //设置新的光标所在位置
                mUsernameEdt.setSelection(str.length());
            }
//            mUsernameEdt.setText(str);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int i = v.getId();
        if (i == R.id.et_password) {
            if (hasFocus) {
                mTilPassword.setStateNormal();
                mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                //上=不为空
                if (!TextUtils.isEmpty(mPasswordEdt.getText().toString().trim())) {
                    //下为空 判断上面格式
                    if (TextUtils.isEmpty(mPasswordAgainEdt.getText().toString().trim())) {
                        //                        if (!isFirstPasswordRight()) {
                        //                            mTilPassword.setStateWrong(mActivity.getResources().getString(R.string.wrong_password));
                        //                            mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                        //                        }
                    } else {//下不为空
                        if (isFirstPasswordRight() || isSecondPasswordRight()) {//上各式合格或者下格式合格
                            if (!mPasswordAgainEdt.getText().toString().trim().equals(mPasswordEdt.getText().toString().trim())) {
                                mTilPassword.setStateWrong(mActivity.getResources().getString(R.string.twice_input_password_must_be_consistent));
                                mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                            } else {
                                mTilPassword.setStateNormal();
                                mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                            }
                        } else {//两个都不合格
                            mTilPassword.setStateWrong(mActivity.getResources().getString(R.string.wrong_password));
                            mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                        }
                    }
                }

            } else if (!hasFocus) {
                //上为空
                if (TextUtils.isEmpty(mPasswordEdt.getText().toString().trim())) {
                    mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c9_e8e9eb));
                    //下为空
                    if (TextUtils.isEmpty(mPasswordAgainEdt.getText().toString().trim())) {
                        mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c9_e8e9eb));
                    } else {//下不为空
                        //判断下格式
                        if (!isSecondPasswordRight()) {
                            mTilPasswordAgain.setStateWrong(mActivity.getResources().getString(R.string.wrong_password));
                        } else {
                            mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c9_e8e9eb));
                        }
                    }

                } else {//上不为空
                    if (TextUtils.isEmpty(mPasswordAgainEdt.getText().toString().trim())) {//下为空
                        if (!isFirstPasswordRight()) {
                            mTilPassword.setStateWrong(mActivity.getResources().getString(R.string.wrong_password));
                            mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                        } else {
                            mTilPassword.setStateNormal();
                            mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                        }
                    } else {//下不为空
                        mTilPasswordAgain.setStateNormal();
                        if (isFirstPasswordRight() || isSecondPasswordRight()) {//上各式合格或者下格式合格
                            if (!mPasswordAgainEdt.getText().toString().trim().equals(mPasswordEdt.getText().toString().trim())) {
                                mTilPassword.setStateWrong(mActivity.getResources().getString(R.string.twice_input_password_must_be_consistent));
                                mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                            } else {
                                mTilPassword.setStateNormal();
                                mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                            }
                        } else {//两个都不合格
                            mTilPassword.setStateWrong(mActivity.getResources().getString(R.string.wrong_password));
                            mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                        }
                    }

                }
            }
        } else if (i == R.id.et_username) {
            mTilUseName.setStateNormal();
        } else if (i == R.id.et_password_again) {
            if (hasFocus) {
                mTilPasswordAgain.setStateNormal();
                //上为空
                if (TextUtils.isEmpty(mPasswordEdt.getText().toString().trim())) {
                    //下不为空
                    if (!TextUtils.isEmpty(mPasswordAgainEdt.getText().toString().trim())) {
                        if (!isSecondPasswordRight()) {
                            mTilPasswordAgain.setStateWrong(mActivity.getResources().getString(R.string.wrong_password));
                        }
                    }
                } else {//上不为空
                    if (!TextUtils.isEmpty(mPasswordAgainEdt.getText().toString().trim())) {
                        if (isFirstPasswordRight() || isSecondPasswordRight()) {//上各式合格或者下格式合格
                            if (!mPasswordAgainEdt.getText().toString().trim().equals(mPasswordEdt.getText().toString().trim())) {
                                mTilPassword.setStateWrong(mActivity.getResources().getString(R.string.twice_input_password_must_be_consistent));
                                mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                            } else {
                                mTilPassword.setStateNormal();
                                mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                            }
                        } else {//两个都不合格
                            mTilPassword.setStateWrong(mActivity.getResources().getString(R.string.wrong_password));
                            mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                        }
                    }

                }
            } else if (!hasFocus) {
                //上为空
                if (TextUtils.isEmpty(mPasswordEdt.getText().toString().trim())) {
                    if (!TextUtils.isEmpty(mPasswordAgainEdt.getText().toString().trim())) {//下不为空
                        if (!isSecondPasswordRight()) {
                            mTilPasswordAgain.setStateWrong(mActivity.getResources().getString(R.string.wrong_password));
                        } else {
                            mTilPasswordAgain.setStateNormal();
                        }

                    }
                } else {//上不为空
                    if (!TextUtils.isEmpty(mPasswordAgainEdt.getText().toString().trim())) {
                        if (isFirstPasswordRight() || isSecondPasswordRight()) {//上各式合格或者下格式合格
                            if (!mPasswordAgainEdt.getText().toString().trim().equals(mPasswordEdt.getText().toString().trim())) {
                                mTilPassword.setStateWrong(mActivity.getResources().getString(R.string.twice_input_password_must_be_consistent));
                                mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                            } else {
                                mTilPassword.setStateNormal();
                                mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                            }
                        } else {//两个都不合格
                            mTilPassword.setStateWrong(mActivity.getResources().getString(R.string.wrong_password));
                            mViewPassword.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                        }
                    }
                }
            }
        }
    }

    private boolean isFirstPasswordRight() {
        if (CheckUtils.isLetterDigit(mPasswordEdt.getText().toString().trim()) && (mPasswordEdt.getText().toString().trim().length() >= 6) && (mPasswordEdt.getText().toString().trim().length() <= 16)) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isSecondPasswordRight() {
        if (CheckUtils.isLetterDigit(mPasswordAgainEdt.getText().toString().trim()) && (mPasswordAgainEdt.getText().toString().trim().length() >= 6) && (mPasswordAgainEdt.getText().toString().trim().length() <= 16)) {
            return true;
        } else {
            return false;
        }
    }

    private void checkUerAccount() {
        showProgressDialog(getString(R.string.submiting));
        Map map = new HashMap();
        map.put("userAccount", mUsernameEdt.getText().toString().trim());
        String password = mPasswordEdt.getText().toString().trim();
        try {
            byte[] data = RSAUtil.encryptByPublicKey(password.getBytes(), RSAUtil.publicKey);
            password = Base64Utils.encodeBase64(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserCenterCommon.getInstance().setPassword(password);
        NoHttpUtils.httpPost(UserCenterConstant.URL_CHECK_USER_ACCOUNT, map, mOnResponseListener, REQUEST_CHECK_USER_ACCOUNT);
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {

        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            if ("0".equals(commonClass.getCode())) {
                UserCenterCommon.getInstance().setUserAccount(mUsernameEdt.getText().toString().trim());
                UserCenterCommon.getInstance().setPasswordCanSee(mPasswordEdt.getText().toString().trim());
                EventBus.getDefault().post("RCUserNamePasswordFragment");
                //用户名校验成功
                popFragment();
            } else {
                mTilUseName.setStateWrong(commonClass.getMsg());
            }
        }

        @Override
        public void onFailed(String result, int what) {
            toast(result);
        }

        @Override
        public void onFinish(int what) {
            dismissProgressDialog();
        }
    };


    public static String stringFilter(String str)throws PatternSyntaxException {
        // 只允许字母和数字和_
        String   regEx  = "[^a-zA-Z0-9\u4E00-\u9FA5_]";
        Pattern   p   =   Pattern.compile(regEx);
        Matcher m   =   p.matcher(str);
        return   m.replaceAll("").trim();
    }
    /**
     * 禁止EditText输入空格
     *
     * @param editText
     */
    private void setEditTextInhibitInputSpace(EditText editText, final int maxLen) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (" ".equals(source)) {
                    return "";
                } else {
                    int dindex = 0;
                    int count = 0;

                    while (count <= maxLen && dindex < dest.length()) {
                        char sindex = dest.charAt(dindex++);
                        if (sindex < 128) {
                            ++count;
                        } else {
                            count += 2;
                        }

                    }

                    if (count > maxLen) {
                        return dest.subSequence(0, dindex - 1);
                    } else {
                        int var11 = 0;

                        while (count <= maxLen && var11 < source.length()) {
                            char c = source.charAt(var11++);
                            if (c < 128) {
                                ++count;
                            } else {
                                count += 2;
                            }
                        }

                        if (count > maxLen) {
                            --var11;
                        }

                        CharacterByteUtils.mCharSequence = source.subSequence(0, var11);
                        return CharacterByteUtils.mCharSequence;
                    }
                }
            }


        };
        editText.setFilters(new InputFilter[]{filter});
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hideSoftKeyBoard(mPasswordEdt);
        hideSoftKeyBoard(mUsernameEdt);
        hideSoftKeyBoard(mPasswordAgainEdt);
    }
}
